package com.asb.utils;

import org.apache.log4j.Logger;

import com.aliyun.teaopenapi.models.Config;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.taobao.api.ApiException;

import cn.hutool.core.util.StrUtil;

public class AccessUtil implements Runnable {

	public static Logger log = Logger.getLogger(AccessUtil.class);

	private static String access_token = "";

	@Override
	public void run() {
		System.out.println("刷新access_token");
		// TODO Auto-generated method stub
		try {
			access_token = accessToken();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			log.error("获得access_token失败", e);
		}
	}

	public static String getAccess_token() throws ApiException {
		return accessToken();
//		if (StrUtil.isBlankIfStr(access_token)) {
//			try {
//				access_token = accessToken();
//			} catch (ApiException e) {
//				// TODO Auto-generated catch block
//				log.error("获得access_token失败", e);
//			}
//		}
//		return access_token;
	}

	public static void setAccess_token(String access_token) {
		AccessUtil.access_token = access_token;
	}

	private static String accessToken() throws ApiException {
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
		OapiGettokenRequest request = new OapiGettokenRequest();
		request.setAppkey(PropertiesKit.getAppkey());
		request.setAppsecret(PropertiesKit.getAppsecret());
		request.setHttpMethod("GET");
		OapiGettokenResponse response = client.execute(request);
		String access_token = response.getAccessToken();
		log.info(System.currentTimeMillis() + " accessToken:" + access_token);

		return access_token;
	}

	public static com.aliyun.dingtalktodo_1_0.Client createClient() throws Exception {
		Config config = new Config();
		config.protocol = "https";
		config.regionId = "central";
		return new com.aliyun.dingtalktodo_1_0.Client(config);
	}

}
